package com.jfinal.bbsapp.common.config;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import com.jfinal.bbsapp.common.kit.SnowFlakeUtil;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;

public class TableShardingAlgorithm implements PreciseShardingAlgorithm<String> {
	@Override
	public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> preciseShardingValue) {
		//配置的分片的sharding-column对应的值 
		String orderid = preciseShardingValue.getValue();
    	Long ctime = SnowFlakeUtil.datetimeBySnowId(Long.valueOf(orderid));
        //需要分库的逻辑表
        //String table = preciseShardingValue.getLogicTableName();
        String targetTable = preciseShardingValue.getLogicTableName() + "_" + timeStamp2Date(ctime,"yyyyMM");
        if (availableTargetNames.contains(targetTable)){
            return targetTable;
        }
        throw new UnsupportedOperationException("无效的表名称: " + targetTable);
	}
	
	public static String timeStamp2Date(Long timestamp,String format) { 
	    if(timestamp == null || timestamp == 0){ 
	        return ""; 
	    } 
	    if(format == null || format.isEmpty()){
	        format = "yyyy-MM-dd HH:mm:ss";
	    }  
	    SimpleDateFormat sdf = new SimpleDateFormat(format); 
	    return sdf.format(new Date(timestamp)); 
	} 
}
